//
//  UIColor+Gradient.m
//  lechuang
//
//  Created by Mr_hi on 2023/3/21.
//  Copyright © 2023 Mooyi. All rights reserved.
//

#import "UIColor+Gradient.h"

@implementation UIColor (Gradient)

+ (instancetype)gradientChange_ColorWithSize:(CGSize)size
                                   direction:(GradientChangeColorDirection)direction
                                  startColor:(UIColor*)startColor
                                    endColor:(UIColor*)endColor {
    if(CGSizeEqualToSize(size,CGSizeZero) || !startColor || !endColor) {
        return nil;
    }
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame=CGRectMake(0,0, size.width, size.height);
    
    CGPoint startPoint = CGPointZero;
    if (direction == GradientChangeColorDirectionDownDiagonal) {
        startPoint =CGPointMake(0.0,1.0);
    }
    gradientLayer.startPoint= startPoint;
    CGPoint endPoint = CGPointZero;
    
    switch(direction) {
        case GradientChangeColorDirectionLevel: {
            endPoint =CGPointMake(1.0,0.0);
        } break;
        case GradientChangeColorDirectionVertical: {
            endPoint =CGPointMake(0.0,1.0);
        } break;
        case GradientChangeColorDirectionUpwardDiagonal: {
            endPoint =CGPointMake(1.0,1.0);
        } break;
        case GradientChangeColorDirectionDownDiagonal: {
            endPoint =CGPointMake(1.0,0.0);
        } break;
    }
    gradientLayer.endPoint= endPoint;
    gradientLayer.colors = @[(__bridge id)startColor.CGColor, (__bridge id)endColor.CGColor];
    UIGraphicsBeginImageContext(size);
    [gradientLayer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage*image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return [UIColor colorWithPatternImage:image];
}

@end
